﻿using Gargoyle.Roton;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Gargoyle.RotonDX9
{
    public class AudioDX9 : Audio
    {
        private Microsoft.DirectX.DirectSound.Buffer buffer;
        private BufferDescription desc;
        private Device dev;
        private Control owner;

        public AudioDX9(int newSampleRate, Control newOwner)
            : base(newSampleRate)
        {
            owner = newOwner;

            dev = new Device();
            dev.SetCooperativeLevel(owner, CooperativeLevel.Normal);
            desc = new BufferDescription();

            desc.CanGetCurrentPosition = false;
            desc.Control3D = false;
            desc.ControlFrequency = false;
            desc.ControlPan = false;
            desc.ControlPositionNotify = false;
            desc.ControlVolume = true;
            desc.LocateInSoftware = true;
        }

        ~AudioDX9()
        {
            if (buffer != null)
                buffer.Dispose();
            if (dev != null)
                dev.Dispose();
        }

        protected override void PlayStream(Stream soundData, bool loop)
        {
            base.PlayStream(soundData, loop);

            buffer = new Microsoft.DirectX.DirectSound.Buffer(PlayingStream, desc, dev);
            buffer.Volume = -800;
            if (loop)
                buffer.Play(0, BufferPlayFlags.Looping);
            else
                buffer.Play(0, BufferPlayFlags.Default);
        }

        protected override void StopStream()
        {
            if (buffer != null)
            {
                buffer.Stop();
                buffer.Dispose();
            }
            base.StopStream();
            buffer = null;
        }
    }
}
